#FileHelper.gd
class_name FileHelper

#非加密存储
static func save(path,data):
	var file = File.new()
	file.open(path,File.WRITE)#File.WRITE是写模式，并且如果文件不存在会自动新建文件
	file.store_string(var2str(data))
	file.close()

#非加密读取
static func read(path,default_data):
	var data = default_data
	var file = File.new()
	file.open(path,File.READ_WRITE)#File.READ_WRITE是读写模式，并且如果文件不存在会自动新建文件
	var content :String = file.get_as_text()
	if not content.empty():
		data = str2var(content)
	file.close()
	return data

#加密存储
static func save_encrypted(path,data,key):
	var file = File.new()
	file.open_encrypted_with_pass(path,File.WRITE,key)
	file.store_string(var2str(data))
	file.close()

#加密读取
static func read_encrypted(path,key,default_data):
	var data = default_data
	var file = File.new()
	file.open_encrypted_with_pass(path,File.READ_WRITE,key)
	var content :String = file.get_as_text()
	if not content.empty():
		data = str2var(content)
	file.close()
	return data

#测试调用
#var weapon = {"gun":"ak47","bullet":123}
#var player_data = {"name":"godot","hp":50,"weapon":weapon}
#save("user://player_data.res",player_data)
#print("普通文件：" + str(read("user://player_data.res",{})))
#save_encrypted("user://player_data.res",player_data, OS.get_unique_id())
#print("加密文件：" + str(read_encrypted("user://player_data.res", OS.get_unique_id(),{})))
#————————————————
#版权声明：本文为CSDN博主「开发游戏的老王」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
#原文链接：https://blog.csdn.net/ttm2d/article/details/103575079

